# coding=utf-8
"""
作者：董新强 
创建时间：2020-5-8
描述：报告管理
"""
from sqlalchemy import or_, and_

from db_models.cat_abilities import CatAbilities
from db_models.cat_test import CatTest
from framework.db_session import DbSession
from framework.msg import ok, failure
from framework.utilities import to_sha256
from services.service_base import ServiceBase


class ReportManage(ServiceBase):
    def __init__(self, usr):
        super().__init__(usr)

    def get_report(self, ability_id):
        """
        获取报告(假设目前能力只存在两层)
        :param ability_id: 能力ID
        :return:
        """
        if not ability_id:
            return failure(msg='尚未完成测试')

        started = False
        main_score, sub_score = 0, 0
        with DbSession.create() as db:
            query = db.query(CatAbilities.id, CatAbilities.pid, CatAbilities.w, CatTest.score, CatTest.status) \
                .filter(or_(CatAbilities.id == ability_id, CatAbilities.pid == ability_id)) \
                .outerjoin(CatTest, and_(CatTest.aid == CatAbilities.id, CatTest.uid == self.uid))
            for id, pid, w, score, status in query:
                if not status:
                    continue

                started = True
                if not pid:
                    main_score = score * w
                    continue
                sub_score += score * w

        if not started:
            return failure(msg='尚未完成测试')

        score = int(main_score if main_score else sub_score)
        escore = to_sha256('%d-%d-%d-%d' % (score, self.uid, score + self.uid, ability_id - self.uid))
        return ok(data={'score': score, 'escore': escore})


if __name__ == '__main__':
    pass
